<template>
	<view class="favorites-page" :style="{ paddingTop: statusBarHeight + 'px' }">
		<!-- 导航栏 -->
		<view class="nav-bar">
			<text class="nav-title">我的收藏</text>
			<text class="edit-btn" @tap="toggleEdit">{{ isEditing ? '完成' : '编辑' }}</text>
		</view>

		<!-- 查询类型选项 -->
		<view class="search-type">
			<view 
				class="type-item" 
				:class="{ active: currentType === 'product' }" 
				@tap="handleTypeChange('product')"
			>
				<text>商品</text>
			</view>
			<view 
				class="type-item" 
				:class="{ active: currentType === 'post' }" 
				@tap="handleTypeChange('post')"
			>
				<text>帖子</text>
			</view>
		</view>

		<!-- 内容区域 - 根据类型切换显示 -->
		<scroll-view scroll-y class="content-container">
			<!-- 收藏商品列表 -->
			<view v-if="currentType === 'product'">
				<view v-if="favoriteProducts.length === 0" class="empty-tip">
					<text>暂无收藏的商品</text>
				</view>
				
				<view 
					v-for="product in favoriteProducts" 
					:key="product.id"
					class="product-item"
				>
					<view class="checkbox" v-if="isEditing" @tap="toggleSelect(product)">
						<text class="iconfont" :class="{ checked: selectedProducts.includes(product.id) }">
							{{ selectedProducts.includes(product.id) ? '✓' : '' }}
						</text>
					</view>
					
					<image :src="product.image" mode="aspectFill" class="product-image"></image>
					
					<view class="product-info">
						<text class="product-name">{{ product.name }}</text>
						<text class="product-price">¥{{ product.price }}</text>
						<text class="product-sales">已售 {{ product.sales }} 件</text>
						
						<view class="action-row">
							<text class="action-btn add-cart" @tap="addToCart(product)">加入购物车</text>
							<text class="action-btn remove" @tap="removeFromFavorites(product, 'product')">
								{{ isEditing ? '删除' : '移除收藏' }}
							</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 收藏帖子列表 -->
			<view v-if="currentType === 'post'">
				<view v-if="favoritePosts.length === 0" class="empty-tip">
					<text>暂无收藏的帖子</text>
				</view>
				
				<view class="post-list">
					<view class="post-card" v-for="(post, index) in favoritePosts" :key="post.postId" @tap="openPostDetail(post)">
						<!-- 图片区域 -->
						<view class="post-image-container" v-if="post.imageUrls && post.imageUrls.length > 0">
							<view class="single-image">
								<image :src="post.imageUrls[0]" mode="aspectFill" class="post-image"></image>
							</view>
							<view class="ai-badge">
								<text class="iconfont">🤖</text>
								<text class="badge-text">AI推荐</text>
							</view>
						</view>
						
						<!-- 标题区域 -->
						<view>
							<text class="title-info">{{ post.title }}</text>
						</view>
						
						<!-- 信息区域 -->
						<view class="post-info">
							<view class="user-info">
								<image :src="post.avatarUrl" mode="aspectFill" class="avatar"></image>
								<view class="user-detail">
									<text class="username">{{ post.nickName }}</text>
									<text class="post-time">{{ formatTime(post.createTime) }}</text>
								</view>
							</view>
							
							<view class="post-actions">
								<view class="action-item">
									<text class="iconfont">❤</text>
									<text class="action-text">{{ post.likeCount }}</text>
								</view>
								<view class="action-item" @tap.stop="handleComment(post)">
									<text class="iconfont">💬</text>
									<text class="action-text">{{ post.commentCount }}</text>
								</view>
								
								<!-- 编辑模式下的删除按钮 -->
								<view class="action-item remove-post" v-if="isEditing" @tap.stop="removeFromFavorites(post, 'post')">
									<text class="iconfont">🗑️</text>
									<text class="action-text">删除</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 编辑模式下的底部操作栏 -->
		<view class="edit-footer" v-if="isEditing && currentType === 'product'">
			<view class="select-all" @tap="selectAll">
				<text class="iconfont" :class="{ checked: allSelected }">✓</text>
				<text>全选</text>
			</view>
			<view class="delete-btn" @tap="batchDelete">
				<text>删除 ({{ selectedCount }})</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import userManager from '@/common/utils/user.js'
import { getFavoriteProductList ,removeFavorite ,addToCartFromFavorite } from '@/api/Productapi.js';
import { selectPostFavorites } from '@/api/post.js'

const statusBarHeight = ref(0)
const isEditing = ref(false)
const currentType = ref('product')
const favoriteProducts = ref([])
const favoritePosts = ref([])
const selectedProducts = ref([])

onMounted(async() => {
	statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight || 20
	// 检查登录
	if (!userManager.user || !userManager.user.userId) {
		uni.showToast({ title: '请先登录', icon: 'none' });
		return;
	}
	
	// 初始加载商品收藏
	await loadFavoriteList();
})

/**
 * 处理查询类型切换
 */
const handleTypeChange = async (type) => {
	currentType.value = type;
	if (type === 'product') {
		await loadFavoriteList();
	} else if (type === 'post') {
		await loadPostFavorites();
	}
	// 切换类型时重置编辑状态
	if (isEditing.value) {
		toggleEdit();
	}
};

/**
 * 加载收藏商品列表
 */
const loadFavoriteList = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const userId = userManager.user.userId;
		const products = await getFavoriteProductList(userId);
		favoriteProducts.value = Array.isArray(products) ? products : [];
	} catch (error) {
		console.error('加载收藏商品失败:', error);
		uni.showToast({ title: '加载失败', icon: 'none' });
	} finally {
		uni.hideLoading();
	}
};

/**
 * 加载收藏帖子列表
 */
const loadPostFavorites = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const userId = userManager.user.userId;
		const posts = await selectPostFavorites(userId);
		// 处理图片URL格式（将逗号分隔的字符串转为数组）
		const formattedPosts = posts.map(post => ({
			...post,
			imageUrls: post.images ? post.images.split(',') : []
		}));
		favoritePosts.value = formattedPosts;
	} catch (error) {
		console.error('加载收藏帖子失败:', error);
		uni.showToast({ title: '加载失败', icon: 'none' });
	} finally {
		uni.hideLoading();
	}
};

// 编辑模式切换
const toggleEdit = () => {
	isEditing.value = !isEditing.value;
	if (!isEditing.value) {
		selectedProducts.value = [];
	}
};

// 单选/取消选择
const toggleSelect = (product) => {
	const index = selectedProducts.value.indexOf(product.id);
	if (index > -1) {
		selectedProducts.value.splice(index, 1);
	} else {
		selectedProducts.value.push(product.id);
	}
};

// 全选/取消全选
const selectAll = () => {
	if (allSelected.value) {
		selectedProducts.value = [];
	} else {
		selectedProducts.value = favoriteProducts.value.map(p => p.id);
	}
};

// 从收藏中移除单个商品
const removeFromFavorites = async (product) => {
	const index = favoriteProducts.value.findIndex(p => p.id === product.id)
	if (index > -1) {
		favoriteProducts.value.splice(index, 1)
	}
	
	// 同时从选中列表中移除
	const selIndex = selectedProducts.value.indexOf(product.id)
	if (selIndex > -1) {
		selectedProducts.value.splice(selIndex, 1)
	}
	
	console.log("收藏商品ID：",product.productId);
	const userId = userManager.user.userId;
	await removeFavorite(userId,product.productId)
	
	uni.showToast({ title: '已移除', icon: 'success' });
}

// 批量删除商品
const batchDelete = () => {
	if (selectedProducts.value.length === 0) return;
	
	selectedProducts.value.forEach(id => {
		const index = favoriteProducts.value.findIndex(p => p.id === id);
		if (index > -1) {
			favoriteProducts.value.splice(index, 1);
		}
	});
	
	selectedProducts.value = [];
	uni.showToast({ title: '已删除', icon: 'success' });
};

// 加入购物车
const addToCart = async (product) => {
  const user = userManager.user;
  if (!user || !user.userId) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }

  try {
    await addToCartFromFavorite(user.userId, product.productId);
    uni.showToast({ title: '已加入购物车，请在购物车中进行规格选择', icon: 'success' });
  } catch (error) {
    uni.showToast({ title: error.message || '加入失败', icon: 'none' });
  }
};

// 打开帖子详情
const openPostDetail = (post) => {
  // 修改跳转路径为/pages/post-detail/post-detail
  uni.navigateTo({
    url: `/pages/post-detail/post-detail?id=${post.postId}`
  });
};

// 处理评论点击
const handleComment = (post) => {
	// 实际项目中跳转到评论区或弹出评论框
	uni.showToast({ title: `查看评论 (${post.commentCount})`, icon: 'none' });
};

// 格式化时间
const formatTime = (timeStr) => {
	// 简单的时间格式化，可根据需求完善
	if (!timeStr) return '';
	return timeStr.replace(' ', ' · ');
};

// 计算属性
const selectedCount = computed(() => selectedProducts.value.length);
const allSelected = computed(() => 
	selectedProducts.value.length === favoriteProducts.value.length && 
	favoriteProducts.value.length > 0
);
</script>

<style scoped>
.favorites-page {
	background-color: #f8f9fa;
	min-height: 100vh;
}

.nav-bar {
	/* position: fixed; */
	top: v-bind(statusBarHeight + 'px');
	left: 0;
	right: 0;
	height: 44px;
	background-color: white;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 16px;
	z-index: 999;
	box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.nav-title {
	font-size: 16px;
	font-weight: 600;
	color: #333;
}

.edit-btn {
	font-size: 14px;
	color: #007AFF;
}

/* 查询类型样式 */
.search-type {
	/* position: fixed; */
	top: v-bind('statusBarHeight + 44 + "px"');
	left: 0;
	right: 0;
	height: 40px;
	background-color: white;
	display: flex;
	z-index: 998;
	border-bottom: 1px solid #eee;
}

.type-item {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	color: #666;
	position: relative;
}

.type-item.active {
	color: #007AFF;
}

.type-item.active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 50%;
	transform: translateX(-50%);
	width: 30px;
	height: 2px;
	background-color: #007AFF;
	border-radius: 1px;
}

/* 内容容器样式 */
.content-container {
	/* 适配顶部导航和类型选择栏高度 */
	margin-top: calc(v-bind('statusBarHeight') + 84px);
	min-height: calc(100vh - calc(v-bind('statusBarHeight') + 84px));
}

.empty-tip {
	text-align: center;
	color: #999;
	padding: 40px 0;
	font-size: 14px;
}

/* 商品项样式 */
.product-item {
	display: flex;
	background-color: white;
	border-radius: 12px;
	padding: 12px;
	margin-bottom: 12px;
	align-items: center;
}

.checkbox {
	width: 24px;
	height: 24px;
	border: 2px solid #ddd;
	border-radius: 50%;
	margin-right: 12px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12px;
	color: white;
	background-color: #007AFF;
	opacity: 0;
	transition: opacity 0.2s;
}

.checkbox.checked {
	opacity: 1;
}

.product-image {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	margin-right: 12px;
	flex-shrink: 0;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.product-name {
	font-size: 15px;
	color: #333;
	margin-bottom: 4px;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.product-price {
	font-size: 16px;
	color: #e63946;
	font-weight: 600;
	margin-bottom: 4px;
}

.product-sales {
	font-size: 12px;
	color: #999;
	margin-bottom: 8px;
}

.action-row {
	display: flex;
	gap: 8px;
}

.action-btn {
	font-size: 12px;
	padding: 4px 8px;
	border-radius: 4px;
}

.add-cart {
	background-color: #007AFF;
	color: white;
}

.remove {
	background-color: #f8f9fa;
	color: #666;
	border: 1px solid #ddd;
}

/* 帖子列表样式 */
.post-list {
	width: 100%;
}

.post-card {
	background-color: white;
	border-radius: 12px;
	padding: 12px;
	margin-bottom: 12px;
}

.post-image-container {
	position: relative;
	width: 100%;
	border-radius: 8px;
	overflow: hidden;
	margin-bottom: 8px;
}

.single-image {
	width: 100%;
	height: 180px;
}

.post-image {
	width: 100%;
	height: 100%;
}

.ai-badge {
	position: absolute;
	top: 8px;
	left: 8px;
	background-color: rgba(0, 0, 0, 0.5);
	color: white;
	font-size: 12px;
	padding: 2px 6px;
	border-radius: 4px;
	display: flex;
	align-items: center;
	gap: 4px;
}

.title-info {
	font-size: 15px;
	color: #333;
	line-height: 1.4;
	margin-bottom: 12px;
	display: block;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
}

.post-info {
	width: 100%;
}

.user-info {
	display: flex;
	align-items: center;
	margin-bottom: 12px;
}

.avatar {
	width: 30px;
	height: 30px;
	border-radius: 50%;
	margin-right: 8px;
}

.user-detail {
	flex: 1;
}

.username {
	font-size: 13px;
	color: #333;
	margin-right: 8px;
}

.post-time {
	font-size: 11px;
	color: #999;
}

.post-actions {
	display: flex;
	align-items: center;
	justify-content: flex-start;
	gap: 20px;
}

.action-item {
	display: flex;
	align-items: center;
	gap: 4px;
	font-size: 12px;
	color: #666;
}

.remove-post {
	color: #e63946;
	margin-left: auto;
}

/* 编辑模式底部栏 */
.edit-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 50px;
	background-color: white;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 16px;
	box-shadow: 0 -1px 3px rgba(0,0,0,0.1);
}

.select-all {
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 14px;
	color: #333;
}

.select-all .iconfont {
	width: 18px;
	height: 18px;
	border: 2px solid #ddd;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 12px;
	color: white;
	background-color: #007AFF;
	transition: all 0.2s;
}

.select-all .checked {
	opacity: 1;
}

.delete-btn {
	background-color: #e63946;
	color: white;
	padding: 8px 24px;
	border-radius: 20px;
	font-size: 14px;
	font-weight: 500;
}
</style>